$(document).ready(function() {
	var OpeoutObj="";
    var VAL ={
        NORMAL     : "0000000"  ,
        EVT_USER   : $("#userId").text(),
        T_XPINQBOX  : "XPINQBOX",
        T_XPBOXHLD  : "XPBOXHLD",
    	T_XPBISOPE  : "XPBISOPE",
    	T_XPLSTDAT  : "XPLSTDAT"
    };
    var domObj = {
		$window : $(window),
		$boxDetailDiv : $("#boxDetailDiv"),
		$boxDetailGrd : $("#boxDetailGrd")
	};
    /**
     * All controls's jquery object/text
     * @type {Object}
     */
    var controlsQuery = {
        W                 : $(window)              ,
        ppBoxIDInput      : $("#ppBoxIDInput")     ,
        holdReasonSelect  : $("#holdReasonSelect") ,
        remarkInput       : $("#remarkInput")      ,

        mainGrd   :{
            grdId     : $("#boxDetailGrd")   ,
            grdPgText : "#boxDetailPg"       ,
            fatherDiv : $("#boxDetailDiv")
        }
    };

    /**
     * All button's jquery object
     * @type {Object}
     */
    var btnQuery = {
        f1 : $("#f1_btn"),
        f7 : $("#f7_btn")
    };

    /**
     * All tool functions
     * @type {Object}
     */
    var toolFunc = {
        resetJqgrid :function(){
//            controlsQuery.W.unbind("onresize");
//            controlsQuery.mainGrd.grdId.setGridWidth(controlsQuery.mainGrd.fatherDiv.width()*0.90);
//            controlsQuery.W.bind("onresize", this);
        },
        clearInput : function(){
            controlsQuery.ppBoxIDInput.val("");
            controlsQuery.remarkInput.val("");
        },
        getBoxInfo : function(box_id){
            var inObj,
                outObj;
            inObj = {
                trx_id      : VAL.T_XPINQBOX,
                action_flg  : 'Q'           ,
                box_id      : box_id
            };
            outObj = comTrxSubSendPostJson(inObj);
            if(outObj.rtn_code == VAL.NORMAL){
                return outObj;
            }else{
                return null;
            }
        },
        /**
         * Set data for select
         * @param dataCnt
         * @param arr
         * @param selVal
         * @param queryObj
         */
        setSelectDate : function(dataCnt, arr, selVal, queryObj){
            var i, realCnt;

            queryObj.empty();
            realCnt = parseInt( dataCnt, 10);

            if( realCnt == 1 ){
                if( arr.hasOwnProperty(selVal)){
                    queryObj.append("<option value="+ arr[selVal] +">"+ arr[selVal] +"</option>");
                }
            }else if( realCnt > 1 ){
                for( i = 0; i < realCnt; i++ ){
                    if( arr[i].hasOwnProperty(selVal)){
                        queryObj.append("<option value="+ arr[i][selVal] +">"+ arr[i][selVal] +"</option>");
                    }
                }
            }
            queryObj.select2({
    	    	theme : "bootstrap"
    	    });
        },
        /**
         * 根据人员，厂别，站点的关系，筛选出可以使用的站点。By CMJ
         */
        iniOpeSelect : function(){
            var inObj;
            var user_id = VAL.EVT_USER;
            var iaryB = {
                user_id     : user_id
            };
            inObj = {
                trx_id      : VAL.T_XPBISOPE,
                action_flg  : 'I',
                iaryB       : iaryB
            };
            OpeoutObj = comTrxSubSendPostJson(inObj);
        },
        
        iniHoldReasonSelect : function(){
            var inObj,outObj;
            var iary = {
        		data_cate:'HLRN'
            };
            inObj = {
                trx_id      : VAL.T_XPLSTDAT,
                action_flg  : 'I',
                iary       : iary
            };
            outObj = comTrxSubSendPostJson(inObj);
            _setSelectDate(outObj.tbl_cnt, outObj.oary, "data_item", "data_item", "#holdReasonSelect", true);
        }
    };

    /**
     * All button click function
     * @type {Object}
     */
    var btnFunc = {
        //Query
        f1_func : function(){
            var inObj,
                outObj,
                box_id;

            box_id = controlsQuery.ppBoxIDInput.val();
            if(!box_id){
                showErrorDialog("","请输入箱号！");
                return false;
            }

            inObj = {
                trx_id : VAL.T_XPINQBOX,
                action_flg : "S",
                box_id : box_id
            };
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
            	/**
    		     * 检查用户是否有权限操作这个箱子。By CMJ
    		     */
            		for(var i=0;i<OpeoutObj.tbl_cnt;i++){
        		    	var Opeoary = OpeoutObj.tbl_cnt>1 ? OpeoutObj.oary[i] : OpeoutObj.oary;
        		    	if($.trim(outObj.nx_ope_id_fk) == Opeoary.ope_id && 
        		    	   $.trim(outObj.nx_ope_ver_fk) == Opeoary.ope_ver){
        		    		 setGridInfo(outObj.table, "#boxDetailGrd");
        		             controlsQuery.ppBoxIDInput.val("");
        		             break;
        		    	}
            		}
            		if(OpeoutObj.tbl_cnt ==0 || i>=OpeoutObj.tbl_cnt){
        		    	showErrorDialog("", "此用户没有权限操作站点["+outObj.nx_ope_id_fk+"]的箱子！");
        			    return false; 
        		    }
                //<--End
            }

        },
        //HOLD
        f7_func : function(){
            var inObj,
                outObj,
                box_id,
                crGrid,
                rowIds,
                firstRowData,
                hld_note;

            crGrid = controlsQuery.mainGrd.grdId;
            rowIds = crGrid.jqGrid('getDataIDs');
            if(rowIds.length === 0 ){
                showErrorDialog("","请先输入箱号查询！");
                return false;
            }

            firstRowData = crGrid.jqGrid('getRowData', rowIds[0]);
            box_id = firstRowData['box_id_fk'];
            if(!box_id){
                showErrorDialog("","箱号异常！");
                return false;
            }

            hld_note = controlsQuery.remarkInput.val();
            rsn_cate1 = 'HOLD';
            rsn_code1 =  controlsQuery.holdReasonSelect.val();            

            inObj = {
                trx_id : VAL.T_XPBOXHLD ,
                action_flg : "H",
                box_id : box_id,
                evt_usr : VAL.EVT_USER,
                hld_note : hld_note,
                rsn_cate1 : rsn_cate1,
                rsn_code1 : rsn_code1
            };
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                showSuccessDialog(box_id + "保留成功");
//                controlsQuery.ppBoxIDInput.val(box_id);
//                btnFunc.f1_func();
                controlsQuery.mainGrd.grdId.jqGrid("clearGridData");
            }
        }
    };

    /**
     * Bind button click action
     */
    var iniButtonAction = function(){
        btnQuery.f1.click(function(){
            btnFunc.f1_func();
        });
        btnQuery.f7.click(function(){
            btnFunc.f7_func();
        });
    };

    /**
     * grid  initialization
     */
    var iniGridInfo = function(){
        var grdInfoCM = [
            {name: 'prd_seq_id',   index: 'prd_seq_id',   label: PRD_SEQ_ID_TAG  ,   width: PRD_SEQ_ID_CLM,hidden:true},
            {name: 'fab_sn',       index: 'fab_sn'    ,   label: PRD_SEQ_ID_TAG  ,   width: PRD_SEQ_ID_CLM},
            {name: 'box_id_fk',    index: 'box_id_fk',    label: BOX_ID_TAG  ,       width: BOX_ID_CLM},
            {name: 'slot_no',      index: 'slot_no',      label: SLOT_NO_TAG,        width: SLOT_NO_CLM},
            {name: 'prd_stat',     index: 'prd_stat',     label: STATUS_TAG ,        width: PRD_STAT_CLM},
            {name: 'sht_ope_msg',  index: 'sht_ope_msg',  label: REMARK_TAG ,        width: SHT_OPE_MSG_CLM},
            {name: 'hld_evt_seq',  index: 'hld_evt_seq',  label: HOLD_SEQ_TAG ,      width: HLD_EVT_SEQ_CLM},
            {name: 'evt_usr',      index: 'evt_usr',      label: EVT_USR,            width: EVT_USR_CLM},
            {name: 'evt_timestamp',index: 'evt_timestamp',label: EVT_TIMESTAMP ,     width: EVT_TIMESTAMP_CLM},
            {name: 'hld_evt_seq',  index: 'hld_evt_seq',  label: HOLD_SEQ_TAG ,        width: SEQ_ID_CLM}
        ];
        controlsQuery.mainGrd.grdId.jqGrid({
            url:"",
            datatype:"local",
            mtype:"POST",
            height:300,
            width:domObj.$boxDetailDiv.width(),
            shrinkToFit:false,
            scroll:true,
            rownumWidth : true,
            resizable : true,
            rowNum:40,
            loadonce:true,
            fixed:true,
            viewrecords:true,
            pager : controlsQuery.mainGrd.grdPgText,
            colModel: grdInfoCM
        });
     };

    /**
     * Other action bind
     */
    var otherActionBind = function(){
        // Reset size of jqgrid when window resize
        controlsQuery.W.resize(function(){
            toolFunc.resetJqgrid();
        });

        //Stop from auto commit
        $("form").submit(function(){
            return false;
        });

        controlsQuery.ppBoxIDInput.keydown(function(event){
            if(event.keyCode === 13){
                btnFunc.f1_func();
            }
        });
    };

    /**
     * Ini contorl's data
     */
    var iniContorlData = function(){
        toolFunc.clearInput();
        
        //get Operation Info
        toolFunc.iniOpeSelect();
        toolFunc.iniHoldReasonSelect();
        //Tool info
//        toolFunc.iniBySelect();
    };

    /**
     * Ini view, data and action bind
     */
    var initializationFunc = function(){
        iniGridInfo();
        iniButtonAction();
        otherActionBind();

        toolFunc.resetJqgrid();

        iniContorlData();
    };

    initializationFunc();
    
    function resizeFnc(){        
    	comResize(controlsQuery.W,controlsQuery.mainGrd.fatherDiv,controlsQuery.mainGrd.grdId);
    };                                                                                         
    resizeFnc();                                                                               
    domObj.$window.resize(function() {                                                         
    	resizeFnc();                                                                             
	});  
});

